package tech.xs.controllear;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.mysql.fabric.xmlrpc.base.Value;
import com.mysql.jdbc.StringUtils;

import tech.xs.entity.User;
import tech.xs.service.UserService;
import tech.xs.util.Constants;

/**
 * @author 作者 Your-Name:席盛
 * @version 创建时间：2020年2月13日 下午5:18:45
 * @类说明
 */
@Controller
@RequestMapping("/user")
public class UserControllear {
	@Resource
	private UserService userService;

	/*
	 * //实现跳转登录页
	 * 
	 * @RequestMapping(value = "/login.action") public String lo() {
	 * System.out.println("实现跳转登录页-------->"); return "login"; }
	 */

	/**
	 * 实现登录
	 * 
	 * @param userCode
	 * @param userPassword
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/login.action", method = RequestMethod.POST)
	public String login(@RequestParam String userCode, @RequestParam String userPassword, HttpSession session,
			HttpServletRequest request) {
		System.out.println(userCode + "-----------" + userPassword);
		User user = userService.login(userCode, userPassword);
		System.out.println("实现登录------------>");
		if (user != null) {
			session.setAttribute(Constants.USER_SESSION, user);
			return "redirect:/user/frame.action";
		} else {
			request.setAttribute("error", "用户名或密码不正确");
			return "login";
		}
	}

	/**
	 * 登录成功后跳转首页
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/frame.action")
	public String frame(HttpSession session) {
		if (session.getAttribute(Constants.USER_SESSION) == null) {
			return "redirect:/user/login.action";
		}
		return "frame";
	}

	/**
	 * 测试异常登录
	 * 
	 * @param userCode
	 * @param userPassword
	 * @return
	 */
	@RequestMapping(value = "/exlogin.action", method = RequestMethod.GET)
	public String exLogin(@RequestParam String userCode, @RequestParam String userPassword) {
		System.out.println("异常信息--------------->");
		System.out.println(userCode + "-----------" + userPassword);
		User user = userService.login(userCode, userPassword);
		if (user == null) {
			throw new RuntimeException("用户名或密码不正确");
		}
		return "redirect:/user/frame.action";
	}

	/**
	 * 跳转异常处理页面
	 * 
	 * @param e
	 * @param request
	 * @return
	 */
	@ExceptionHandler(value = { RuntimeException.class })
	public String handlerException(RuntimeException e, HttpServletRequest request) {
		System.out.println("handlerException--------------->");
		request.setAttribute("e", e);
		return "error";
	}

	/**
	 * 打开用户管理页面第一次请求
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/userlist.action", method = RequestMethod.GET)
	public String getuserList(Model model) {
		List<User> list = userService.getUserList(null, 0, 0, Constants.pageSize);
		model.addAttribute("userList", list);
		int totalPageCount = 0;
		int totalcount = userService.getUserCount(null, 0);
		if (totalcount % Constants.pageSize == 0) {
			totalPageCount = totalcount / Constants.pageSize;
		} else {
			totalPageCount = totalcount / Constants.pageSize + 1;
		}
		model.addAttribute("currentPageNo", 1);
		System.out.println("1一共" + totalPageCount + "页");
		model.addAttribute("totalCount", totalcount);
		System.out.println("1数据：" + totalcount + "条");
		model.addAttribute("totalPageCount", totalPageCount);
		System.out.println("1一共" + totalPageCount + "页");
		return "userlist";
	}

	/**
	 * 模糊查询，角色查询
	 * 
	 * @param queryname
	 * @param queryUserRole
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/twouserlist.action", method = RequestMethod.POST)
	public String UserPage(String queryname, int queryUserRole, Integer pageIndex, Model model) {
		System.out.println("2现在第" + pageIndex + "页");
		System.out.println("2-");
		System.out.println(queryname);
		System.out.println(queryUserRole);
		System.out.println(pageIndex);
		System.out.println("2-");
		List<User> list = userService.getUserList(queryname, queryUserRole, (pageIndex - 1) * Constants.pageSize,
				Constants.pageSize);
		model.addAttribute("userList", list);
		int totalPageCount = 0;
		int totalcount = userService.getUserCount(queryname, queryUserRole);
		if (totalcount % Constants.pageSize == 0) {
			totalPageCount = totalcount / Constants.pageSize;
		} else {
			totalPageCount = totalcount / Constants.pageSize + 1;
		}
		model.addAttribute("currentPageNo", pageIndex);
		System.out.println("2一共" + totalPageCount + "页");
		model.addAttribute("totalCount", totalcount);
		System.out.println("2数据：" + totalcount + "条");
		model.addAttribute("totalPageCount", totalPageCount);
		System.out.println("2一共" + totalPageCount + "页");
		return "userlist";
	}

	/**
	 * useradd打开添加页
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/useradd.action", method = RequestMethod.GET)
	public String UserAdd(@ModelAttribute("user") User user) {
		return "useradd";
	}

	/**
	 * useradd添加页
	 * 
	 * @param user
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/useradd.action", method = RequestMethod.POST)
	public String userAdd(User user, HttpSession session, HttpServletRequest request,
			@RequestParam(value = "attachs", required = false) MultipartFile[] attachs) {
		String idPicPath = null;
		String workPicPath = null;
		String errorinfo = null;
		boolean flag = true;
		// 定义上传目录路径
		String path = "D://upload//";
		System.out.println(path);
		for (int i = 0; i < attachs.length; i++) {
			MultipartFile attach = attachs[i];

			// 判断文件是否为空
			if (!attach.isEmpty()) {

				if (i == 0) {
					errorinfo = "uploadFileError";
				} else if (i == 1) {
					errorinfo = "uploadWpError";
				}

				// 获取原文件名
				String oldFileName = attach.getOriginalFilename();
				System.out.println(oldFileName);

				// 获取源文件后缀字节，并对文件后缀进行判断
				String prefix = FilenameUtils.getExtension(oldFileName);
				System.out.println(prefix);

				// 获取原文件大小，并于规定的上传大小进行比较，如超过规定大小，给予提示
				int filesize = 500000;
				System.out.println(attach.getSize());
				if (attach.getSize() > filesize) { // 上传大小不得超过500kb
					request.setAttribute(errorinfo, " * 上传大小不得超过500kb！");
					flag = false;

					// 判断若不符合规定（jpg,jpeg,png,pneg），则给予提示
				} else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
						|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) { // 上传格式不正确

					// RandomUtile来获取0-100000以内的随机数
					// 若满足以上规定（文件大小，文件后缀），则可以进行文件上传操作。首先定义新的文件名（当前时间+随机数+"_Personal.jpg"），以保证不会重复，并根据新的文件名和目标来创建一个File对象（该对象用户来接受用户上传的文件流），若不存在则自动创建
					String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + oldFileName;
					System.out.println(attach.getName());
					File targerFile = new File(path + fileName);
					if (!targerFile.exists()) {
						targerFile.mkdirs();
					}

					try {

						// 调用MultipartFile的transferTo(targetFile)方法，把MultipartFile中文件流的数据输出至目标文件中
						attach.transferTo(targerFile);

					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						request.setAttribute(errorinfo, " * 上传失败！");
						flag = false;
					}

					if (i == 0) {
						idPicPath = fileName;
					} else if (i == 1) {
						workPicPath = fileName;
					}

				} else {
					request.setAttribute(errorinfo, " * 上传图片格式不正确！");
					flag = false;
				}
			}
		}

		if (flag) {

			user.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
			user.setCreationDate(new Date());

			// 设置user对象的idPicPath属性(记录上传文件的路径)，最后调用userService的add()方法，进行数据保持
			user.setIdPicPath(idPicPath);
			user.setWorkPicPath(workPicPath);

			System.out.println("userAdd--------------->");
			boolean l = userService.add(user);
			if (l) {
				return "redirect:/user/userlist.action";
			} else {
				return "useradd";
			}
		}
		return "useradd";
	}

	/**
	 * springfm打开添加页
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/springfm.action", method = RequestMethod.GET)
	public String springfm(@ModelAttribute("user") User user) {
		return "springfm";
	}

	/**
	 * springfm添加页
	 * 
	 * @param user
	 * @param bindingResult
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/springfm.action", method = RequestMethod.POST)
	public String Springfm(@Valid User user, BindingResult bindingResult, HttpSession session) {
		if (bindingResult.hasErrors()) {
			System.out.println("bindingResult.hasErrors-------->");
			return "springfm";
		}
		user.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
		user.setCreationDate(new Date());
		System.out.println("Springfm--------------->");
		boolean l = userService.add(user);
		if (l) {
			return "redirect:/user/userlist.action";
		} else {
			return "springfm";
		}
	}

	/**
	 * 回显
	 * 
	 * @param uid
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/usermodify.action", method = RequestMethod.GET)
	public String usermodify(@RequestParam Integer uid, Model model) {
		System.out.println("usermodify--------------->");
		System.out.println(uid);
		User user = userService.getUserById(uid);
		model.addAttribute("user", user);
		return "usermodify";
	}

	/**
	 * 修改
	 * 
	 * @param user
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/usermodify.action", method = RequestMethod.POST)
	public String userModify(User user, HttpSession session) {
		user.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
		user.setCreationDate(new Date());
		System.out.println("userModify------------->");
		System.out.println(user);
		boolean l = userService.modify(user);
		if (l) {
			return "redirect:/user/userlist.action";
		} else {
			return "usermodify";
		}
	}

	/**
	 * 查看
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
	public String userview(@PathVariable Integer id, Model model) {
		System.out.println("userview--------------->");
		System.out.println(id);
		User user = userService.getUserById(id);
		model.addAttribute("user", user);
		return "userview";
	}

	/**
	 * 实现删除
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/delete.action",method = RequestMethod.GET)
	@ResponseBody
	public Object delete(@RequestParam Integer id) {
		System.out.println("delete----------->"+id);
		HashMap<String, String>resultMap=new HashMap<String, String>();
		if (id == null) {
			resultMap.put("id", "noexist");
		}else {
			boolean l = userService.deleteUserById(id);
			if (l) 
				resultMap.put("id", "true");
			else
				resultMap.put("id", "false");
		}
		return JSONArray.toJSONString(resultMap);
	}
	/**
	 * 实现编码校验
	 * @param userCode
	 * @return
	 */
	@RequestMapping(value ="/userCodeIsExit.action",method = RequestMethod.GET)
	@ResponseBody   //标注该注解的处理结果直接写入HTTP    异步获取数据将输出到相应流中
	public Object userCodeIsExit(@RequestParam String userCode) {
		System.out.println("userCodeIsExit------------->");
		HashMap<String, String> resultMap=new HashMap<String, String>();
		if (StringUtils.isNullOrEmpty(userCode)) {
			resultMap.put("userCode", "exist");
		}else {
			User user= userService.getUserCode(userCode);
			if (user != null) 
				resultMap.put("userCode", "exist");
			else
				resultMap.put("userCode", "noexist");
			
		}
		return JSONArray.toJSONString(resultMap);
	}
}
